import * as THREE from 'three';
import { AxesHelper, Color } from 'three';
import BaseThreeApp from '../BaseThreeApp';
import DebugInfo from '../DebugInfo';
const TWEEN = require('@tweenjs/tween.js').default;

class _2_1AxesHelp extends BaseThreeApp {
  public scene: THREE.Scene;
  public camera: THREE.Camera;
  public renderer: THREE.WebGLRenderer;
  public cube: THREE.Mesh;

  create() {
    return super.create();
  }

  start() {
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(
      60,
      this.clientWidth / this.clientHeight,
      0.1,
      1000
    );
    this.camera.position.z = 5;

    this.renderer = new THREE.WebGLRenderer({
      canvas: this.element,
    });

    this.renderer.setDrawingBufferSize(this.clientWidth, this.clientHeight, 1);

    const geometry = new THREE.BoxGeometry(1, 1, 1);
    // geometry.computeVertexNormals();
    const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
    this.cube = new THREE.Mesh(geometry, material);
    this.scene.add(this.cube);

    const helper = new AxesHelper(2);
    this.cube.add(helper);

    console.log(TWEEN.Tween);
    const coord = { x: 0 };
    const animation = new TWEEN.Tween(coord);
    animation
      .to({ x: 2 }, 2000)
      .repeat(10)
      .onUpdate(() => {
        this.cube.position.x = coord.x;
      })
      .start();
    this.isRunning = true;
    const animate = (time) => {
      if (!this.isRunning || this.element === null) {
        return;
      }
      DebugInfo.Instance.begin();

      this.renderer.render(this.scene, this.camera);

      this.cube.rotation.x = 0.001 * time;
      this.cube.rotation.y = 0.001 * time;

      TWEEN.update(time);
      DebugInfo.Instance.end();
      // const m = this.cube.matrixWorld;
      // helper.setRotationFromEuler(this.cube.rotation);

      requestAnimationFrame(animate);
    };
    animate(0);
  }

  onresize(e: UIEvent) {
    super.onresize(e);
    console.log('onresive');
    if (this.renderer) {
      this.renderer.setDrawingBufferSize(
        this.clientWidth,
        this.clientHeight,
        1
      );
      if (this.camera && this.camera instanceof THREE.PerspectiveCamera) {
        this.camera.aspect = this.clientWidth / this.clientHeight;
        this.camera.updateProjectionMatrix();
      }
    }
  }
}

export default new _2_1AxesHelp();
